package com.qf.shiro;


import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Ypl
 * @version V1.0
 * @Project September-mavens
 * @Package com.qf.shiro
 * @Description:
 * @Date 2022/10/12 17:53
 */
@SuppressWarnings("all")
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    DtsAdminService dtsAdminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService dtsPermissionService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        获取用户
        DtsAdmin admin = (DtsAdmin) principals.getPrimaryPrincipal();
//        获取角色ID
        Integer[] roleIds = admin.getRoleIds();
//        查询用户对应的角色

        //要一个角色set集合

        info.setRoles(roleService.findRoleByIds(roleIds));
        //要一个权限集合
        info.setStringPermissions(dtsPermissionService.finfPsmByIds(roleIds));

        return info;
    }

    /**
     * 认证
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取token中的账户和密码
        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());

//        进行认证
        DtsAdmin admin = dtsAdminService.findByUserName(username);
        //1.是否匹配
        if(admin==null){
            throw new UnknownAccountException("未知用户");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(password);
        //密码校验
        if(!passwordEncoder.matches(password,encode)){
            throw new CredentialsException("密码错误");
        }
        //是否被锁定
        if(admin.getDeleted()){
            throw new LockedAccountException("账户被锁定");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin,password,admin.getUsername());

        return info;
    }
}
